var url = require('url');
var queryString = require('querystring');
var models = require('./models');
var async = require('async');
var cheerio = require('cheerio');
var fs = require('fs');

function ViewServer(){
	this.$frame = cheerio.load(fs.readFileSync('./frame/frame.html', 'ascii'));
	
	this.cache = this.CacheViews();
}

ViewServer.prototype.CacheViews = function(){
	var files = fs.readdirSync('./views');
	var cache = {}
	files.map(function(file){
		console.log('Caching: '+file);
		
		var view_name = file.split('.')[0];
		cache[view_name] = cheerio.load(fs.readFileSync('./views/'+file, 'ascii'));
	});
	return cache;
}

ViewServer.prototype.Serve = function(request, response){
	console.log(request.url);
	if(request.session.user == undefined){
        request.url = '/view/home';
    }
        
	var view = request.url.split('/').last().split('.')[0].split('?')[0];
	console.log('Serving view: '+view);
	//This is probably slow
	var $new = cheerio.load(this.$frame.html());
	var $content = this.cache[view];
	if(!$content.html){
		console.log('View not found: '+view);
		response.status(404).send('View not found');
	}
	$new('div#content').append($content.html());
	console.log('About to send...');
	response.send($new.html());	
	console.log('sent');
}

exports.ViewServer = ViewServer;